<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>License Guard - 授权管理器（管理员专用）</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            max-width: 700px;
            width: 100%;
            padding: 40px;
        }

        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 10px;
            font-size: 28px;
        }

        .warning {
            background: #fff3cd;
            border: 2px solid #ffc107;
            color: #856404;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 30px;
            text-align: center;
            font-weight: 600;
        }

        .subtitle {
            text-align: center;
            color: #666;
            margin-bottom: 30px;
            font-size: 14px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 500;
        }

        input, select, textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s;
        }

        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }

        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 14px 30px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            width: 100%;
            margin-top: 10px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        .btn-secondary {
            background: #6c757d;
        }

        .btn-danger {
            background: #dc3545;
        }

        .result-box {
            margin-top: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            display: none;
        }

        .result-box.show {
            display: block;
            animation: fadeIn 0.5s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .license-key {
            background: #fff;
            padding: 15px;
            border-radius: 8px;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            word-break: break-all;
            margin: 10px 0;
            border: 2px solid #28a745;
            position: relative;
        }

        .info-grid {
            display: grid;
            grid-template-columns: auto 1fr;
            gap: 10px;
            margin-top: 15px;
        }

        .info-label {
            font-weight: 600;
            color: #555;
        }

        .info-value {
            color: #333;
        }

        .tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 2px solid #e0e0e0;
        }

        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border: none;
            background: none;
            color: #666;
            font-weight: 500;
            transition: all 0.3s;
        }

        .tab.active {
            color: #667eea;
            border-bottom: 3px solid #667eea;
            margin-bottom: -2px;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .license-list {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 10px;
        }

        .license-item {
            padding: 10px;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .license-item:last-child {
            border-bottom: none;
        }

        .status-badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        .status-active {
            background: #d4edda;
            color: #155724;
        }

        .status-expired {
            background: #f8d7da;
            color: #721c24;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔐 授权管理器</h1>
        <p class="subtitle">License Guard v2.0 - 管理员控制台 <span style="opacity: 0.7; font-style: italic;">by Chaxi</span></p>
        
        <div class="warning">
            ⚠️ 此工具仅供管理员使用！请勿分发给客户！
        </div>

        <div class="tabs">
            <button class="tab active" onclick="switchTab('generate')">生成授权</button>
            <button class="tab" onclick="switchTab('manage')">管理授权</button>
            <button class="tab" onclick="switchTab('batch')">批量生成</button>
        </div>

        <!-- 生成授权标签页 -->
        <div id="generate-tab" class="tab-content active">
            <form id="license-form">
                <div class="form-group">
                    <label for="machine-id">目标机器ID *</label>
                    <input type="text" id="machine-id" name="machineId" required 
                           placeholder="从客户处获取的机器ID">
                </div>

                <div class="row">
                    <div class="form-group">
                        <label for="license-type">授权类型</label>
                        <select id="license-type" name="type">
                            <option value="trial">试用版 (30天)</option>
                            <option value="standard">标准版 (365天)</option>
                            <option value="enterprise">企业版 (永久)</option>
                            <option value="custom">自定义</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="duration">有效期</label>
                        <input type="number" id="duration" name="duration" value="30" min="1">
                    </div>
                </div>

                <div class="form-group" id="custom-duration" style="display: none;">
                    <label for="duration-unit">时间单位</label>
                    <select id="duration-unit" name="unit">
                        <option value="days">天</option>
                        <option value="months">月</option>
                        <option value="years">年</option>
                    </select>
                </div>

                <div class="row">
                    <div class="form-group">
                        <label for="customer-name">客户名称</label>
                        <input type="text" id="customer-name" name="customerName" 
                               placeholder="公司或个人名称">
                    </div>

                    <div class="form-group">
                        <label for="customer-email">客户邮箱</label>
                        <input type="email" id="customer-email" name="customerEmail" 
                               placeholder="contact@example.com">
                    </div>
                </div>

                <div class="form-group">
                    <label for="max-activations">最大激活数</label>
                    <input type="number" id="max-activations" name="maxActivations" value="1" min="1">
                </div>

                <div class="form-group">
                    <label for="features">功能权限</label>
                    <input type="text" id="features" name="features" 
                           value="basic" placeholder="basic,advanced,premium (逗号分隔)">
                </div>

                <div class="form-group">
                    <label for="notes">备注</label>
                    <textarea id="notes" name="notes" rows="2" 
                              placeholder="内部备注，不会包含在授权中"></textarea>
                </div>

                <button type="submit" class="btn">生成授权码</button>
            </form>

            <div id="result" class="result-box">
                <h3>✅ 授权生成成功</h3>
                <p style="margin: 10px 0; color: #666;">请将以下授权码发送给客户：</p>
                <div class="license-key" id="license-key"></div>
                <button class="btn" onclick="copyLicense()">复制授权码</button>
                <button class="btn btn-secondary" onclick="saveLicense()">保存到文件</button>
                
                <div class="info-grid">
                    <span class="info-label">授权ID:</span>
                    <span class="info-value" id="license-id"></span>
                    
                    <span class="info-label">客户:</span>
                    <span class="info-value" id="customer-display"></span>
                    
                    <span class="info-label">类型:</span>
                    <span class="info-value" id="license-type-display"></span>
                    
                    <span class="info-label">过期时间:</span>
                    <span class="info-value" id="expiry-date"></span>
                    
                    <span class="info-label">机器ID:</span>
                    <span class="info-value" id="machine-id-display" style="font-family: monospace;"></span>
                </div>
            </div>
        </div>

        <!-- 管理授权标签页 -->
        <div id="manage-tab" class="tab-content">
            <div class="form-group">
                <label>已生成的授权记录</label>
                <div class="license-list" id="license-list">
                    <p style="text-align: center; color: #999;">暂无授权记录</p>
                </div>
            </div>

            <div class="form-group">
                <label for="revoke-id">撤销授权</label>
                <input type="text" id="revoke-id" placeholder="输入授权ID">
                <button class="btn btn-danger" onclick="revokeLicense()">撤销授权</button>
            </div>

            <div class="form-group">
                <button class="btn" onclick="exportRecords()">导出所有记录</button>
                <button class="btn btn-secondary" onclick="clearRecords()">清空记录</button>
            </div>
        </div>

        <!-- 批量生成标签页 -->
        <div id="batch-tab" class="tab-content">
            <form id="batch-form">
                <div class="form-group">
                    <label for="batch-type">授权类型</label>
                    <select id="batch-type" name="type">
                        <option value="trial">试用版</option>
                        <option value="standard">标准版</option>
                        <option value="enterprise">企业版</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="batch-count">生成数量</label>
                    <input type="number" id="batch-count" name="count" value="10" min="1" max="100">
                </div>

                <div class="form-group">
                    <label for="batch-prefix">批次前缀</label>
                    <input type="text" id="batch-prefix" name="prefix" 
                           placeholder="例如: BATCH-2024-01">
                </div>

                <button type="submit" class="btn">批量生成</button>
            </form>

            <div id="batch-result" class="result-box">
                <h3>批量生成完成</h3>
                <p id="batch-summary"></p>
                <button class="btn" onclick="downloadBatch()">下载所有授权码</button>
            </div>
        </div>
    </div>

    <script>
        // 授权记录存储
        let licenseRecords = JSON.parse(localStorage.getItem('licenseRecords') || '[]');
        let currentBatch = [];

        // 切换标签页
        function switchTab(tabName) {
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });

            document.getElementById(tabName + '-tab').classList.add('active');
            event.target.classList.add('active');

            if (tabName === 'manage') {
                updateLicenseList();
            }
        }

        // 监听授权类型变化
        document.getElementById('license-type').addEventListener('change', function(e) {
            const customDuration = document.getElementById('custom-duration');
            const durationInput = document.getElementById('duration');
            
            if (e.target.value === 'custom') {
                customDuration.style.display = 'block';
            } else {
                customDuration.style.display = 'none';
                
                switch(e.target.value) {
                    case 'trial':
                        durationInput.value = 30;
                        break;
                    case 'standard':
                        durationInput.value = 365;
                        break;
                    case 'enterprise':
                        durationInput.value = 9999;
                        break;
                }
            }
        });

        // 生成授权
        document.getElementById('license-form').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(e.target);
            const licenseData = {
                type: formData.get('type'),
                machineId: formData.get('machineId'),
                duration: parseInt(formData.get('duration')),
                unit: formData.get('unit') || 'days',
                customerName: formData.get('customerName'),
                customerEmail: formData.get('customerEmail'),
                maxActivations: parseInt(formData.get('maxActivations')),
                features: formData.get('features').split(',').map(f => f.trim()),
                notes: formData.get('notes')
            };

            // 实际生成授权码（这里是模拟）
            const license = generateRealLicense(licenseData);
            
            // 保存记录
            const record = {
                ...license,
                customerName: licenseData.customerName,
                customerEmail: licenseData.customerEmail,
                notes: licenseData.notes,
                createdAt: new Date().toISOString()
            };
            licenseRecords.push(record);
            localStorage.setItem('licenseRecords', JSON.stringify(licenseRecords));
            
            // 显示结果
            displayLicense(license, licenseData);
        });

        // 实际的授权生成（生成兼容Electron版本的授权码）
        function generateRealLicense(data) {
            // 生成唯一ID
            const licenseId = 'LIC-' + Date.now().toString(36).toUpperCase();
            
    // 根据授权类型设置实际持续时间
    let actualDuration = data.duration;
    let actualUnit = data.unit || 'days';
    
    // 总是强制根据授权类型设置正确的持续时间
    if (data.type === 'trial') {
        actualDuration = 30;
        actualUnit = 'days';
    } else if (data.type === 'standard') {
        actualDuration = 365;
        actualUnit = 'days';
    } else if (data.type === 'enterprise') {
        actualDuration = 36500; // 约100年，实际上是永久
        actualUnit = 'days';
    } else if (data.type === 'custom') {
        // 对于自定义类型，使用表单中设置的值
        actualDuration = data.duration;
        actualUnit = data.unit || 'days';
    }
            
            console.log(`生成授权: 类型=${data.type}, 持续时间=${actualDuration} ${actualUnit}`);
            
            // 计算过期时间
            const now = new Date();
            const expiryDate = new Date(now);
            if (actualUnit === 'days') {
                expiryDate.setDate(expiryDate.getDate() + actualDuration);
            } else if (actualUnit === 'months') {
                expiryDate.setMonth(expiryDate.getMonth() + actualDuration);
            } else if (actualUnit === 'years') {
                expiryDate.setFullYear(expiryDate.getFullYear() + actualDuration);
            }
            
            // 构建授权信息
            const licenseInfo = {
                id: licenseId,
                type: data.type,
                version: '2.0', // 确保使用兼容版本
                machineId: data.machineId,
                systemInfo: {
                    os: navigator.platform,
                    browser: navigator.userAgent,
                    timestamp: Date.now()
                },
                issueDate: now.toISOString(),
                expiryDate: expiryDate.toISOString(),
                duration: actualDuration, // 使用修正后的持续时间
                unit: actualUnit, // 使用修正后的时间单位
                features: data.features,
                maxActivations: data.maxActivations || 1,
                metadata: {
                    customerName: data.customerName || '未指定',
                    customerEmail: data.customerEmail || '',
                    issuer: 'Web Keygen',
                    timestamp: Date.now()
                },
                nonce: generateRandomString(32)
            };
            
            // 序列化并签名（实际版本会使用RSA）
            const dataString = JSON.stringify(licenseInfo);
            const signature = btoa(dataString); // 简化版签名，实际应使用RSA
            
            // 组合成授权码格式
            const combined = {
                data: dataString,
                signature: signature
            };
            
            // Base64编码最终结果
            const licenseKey = btoa(JSON.stringify(combined));
            
            // 生成格式化的授权码（每5个字符添加一个连字符）
            const formattedKey = licenseKey.match(/.{1,5}/g)?.join('-') || licenseKey;
            
            return {
                key: formattedKey,
                id: licenseId,
                type: data.type,
                machineId: data.machineId,
                expiryDate: expiryDate.toLocaleDateString(),
                features: data.features
            };
        }
        
        // 生成随机字符串
        function generateRandomString(length) {
            const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            let result = '';
            for (let i = 0; i < length; i++) {
                result += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            return result;
        }

        // 计算过期日期
        function calculateExpiryDate(duration, unit) {
            const date = new Date();
            if (unit === 'days') {
                date.setDate(date.getDate() + duration);
            } else if (unit === 'months') {
                date.setMonth(date.getMonth() + duration);
            } else if (unit === 'years') {
                date.setFullYear(date.getFullYear() + duration);
            }
            return date.toLocaleDateString();
        }

        // 显示授权信息
        function displayLicense(license, data) {
            document.getElementById('license-key').textContent = license.key;
            document.getElementById('license-id').textContent = license.id;
            document.getElementById('customer-display').textContent = 
                data.customerName || '未指定';
            document.getElementById('license-type-display').textContent = license.type;
            document.getElementById('expiry-date').textContent = license.expiryDate;
            document.getElementById('machine-id-display').textContent = license.machineId;
            
            document.getElementById('result').classList.add('show');
        }

        // 复制授权码
        function copyLicense() {
            const licenseKey = document.getElementById('license-key').textContent;
            navigator.clipboard.writeText(licenseKey).then(() => {
                alert('授权码已复制到剪贴板！');
            });
        }

        // 保存授权到文件
        function saveLicense() {
            const licenseKey = document.getElementById('license-key').textContent;
            const licenseId = document.getElementById('license-id').textContent;
            const customer = document.getElementById('customer-display').textContent;
            
            const content = `License Guard 授权信息
====================================
授权ID: ${licenseId}
客户: ${customer}
生成时间: ${new Date().toLocaleString()}
====================================

授权码:
${licenseKey}

====================================
请妥善保管此授权码！
`;
            
            const blob = new Blob([content], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `license_${licenseId}.txt`;
            a.click();
        }

        // 更新授权列表
        function updateLicenseList() {
            const listDiv = document.getElementById('license-list');
            if (licenseRecords.length === 0) {
                listDiv.innerHTML = '<p style="text-align: center; color: #999;">暂无授权记录</p>';
                return;
            }
            
            listDiv.innerHTML = licenseRecords.map(record => `
                <div class="license-item">
                    <div>
                        <strong>${record.id}</strong><br>
                        <small>${record.customerName || '未命名'} - ${record.machineId.substring(0, 8)}...</small>
                    </div>
                    <span class="status-badge status-active">有效</span>
                </div>
            `).join('');
        }

        // 批量生成
        document.getElementById('batch-form').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const type = document.getElementById('batch-type').value;
            const count = parseInt(document.getElementById('batch-count').value);
            const prefix = document.getElementById('batch-prefix').value;
            
            currentBatch = [];
            for (let i = 0; i < count; i++) {
                const license = generateRealLicense({
                    type: type,
                    machineId: 'UNASSIGNED',
                    duration: type === 'trial' ? 30 : (type === 'standard' ? 365 : 9999),
                    features: ['basic']
                });
                
                if (prefix) {
                    license.id = `${prefix}-${i + 1}`;
                }
                
                currentBatch.push(license);
            }
            
            document.getElementById('batch-summary').textContent = 
                `成功生成 ${count} 个 ${type} 授权码`;
            document.getElementById('batch-result').classList.add('show');
        });

        // 下载批量授权
        function downloadBatch() {
            const content = currentBatch.map(license => 
                `${license.id}\t${license.key}`
            ).join('\n');
            
            const blob = new Blob([content], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `batch_licenses_${Date.now()}.txt`;
            a.click();
        }

        // 导出记录
        function exportRecords() {
            const blob = new Blob([JSON.stringify(licenseRecords, null, 2)], 
                { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `license_records_${Date.now()}.json`;
            a.click();
        }

        // 清空记录
        function clearRecords() {
            if (confirm('确定要清空所有授权记录吗？此操作不可恢复！')) {
                licenseRecords = [];
                localStorage.setItem('licenseRecords', JSON.stringify(licenseRecords));
                updateLicenseList();
                alert('记录已清空');
            }
        }
    </script>
</body>
</html>
